package com.pan.admin.module.loanProduct.service.impl;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.pan.admin.common.exception.ServiceException;
import com.pan.admin.common.utils.DateUtils;
import com.pan.admin.common.utils.SecurityUtils;
import com.pan.admin.module.loanProduct.dao.LoanProductPlanDao;
import com.pan.admin.module.loanProduct.dao.LoanProductPlanFilterChannelDao;
import com.pan.admin.module.loanProduct.entity.LoanProductPlan;
import com.pan.admin.module.loanProduct.entity.po.LoanProductPlanFilterChannelPO;
import com.pan.admin.module.loanProduct.service.LoanProductPlanFilterChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LoanProductPlanFilterChannelServiceImpl implements LoanProductPlanFilterChannelService {

    @Autowired
    private LoanProductPlanDao loanProductPlanDao;
    @Autowired
    private LoanProductPlanFilterChannelDao loanProductPlanFilterChannelDao;

    @Override
    @Transactional(readOnly = true)
    public List<LoanProductPlanFilterChannelPO> list(Long loanProductId, Long loanProductPlanId) {
        return loanProductPlanFilterChannelDao.list(loanProductId, loanProductPlanId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Long loanProductPlanId, List<Long> loanChannelIds) {
        //  删除原有
        loanProductPlanFilterChannelDao.deleteByProductPlanId(loanProductPlanId);

        //  新增
        if (ValidParam.isNotEmpty(loanChannelIds)) {
            LoanProductPlan loanProductPlan = loanProductPlanDao.getById(loanProductPlanId);
            Assert.isNotNullThrows(loanProductPlan, new ServiceException("非法更新"));

            List<LoanProductPlanFilterChannelPO> batchInsert = CollUtils.newArrayList(loanChannelIds.size());

            IteratorUtils.array(loanChannelIds, channelId -> {
                LoanProductPlanFilterChannelPO loanProductPlanFilterChannelPO = new LoanProductPlanFilterChannelPO();
                loanProductPlanFilterChannelPO.setLoanProductId(loanProductPlan.getLoanProductId());
                loanProductPlanFilterChannelPO.setLoanProductPlanId(loanProductPlan.getId());
                loanProductPlanFilterChannelPO.setLoanChannelId(channelId);
                loanProductPlanFilterChannelPO.setCreateBy(SecurityUtils.getUsername());
                loanProductPlanFilterChannelPO.setCreateTime(DateUtils.getNowDate());
                batchInsert.add(loanProductPlanFilterChannelPO);
            });

            loanProductPlanFilterChannelDao.batchInsertByProductPlanId(batchInsert);
        }
    }

}
